<?php
namespace Admin\Controller;

class RoleController extends CommonController{
	public function add(){
		if(IS_GET){
			//显示页面
			$this->display();
		}else{
			//处理提交
			$Model = D("Role");
			$data = $Model->create();
			if(!$data){
				$this->error($Model->getError());
			}
			$res = $Model->add($data);
			if(!$res){
				$this->error("添加失败");
			}
			$this->success("添加成功");
		}
	}
	public function index(){
		$Model = D("Role");
		$data = $Model->listData();
		if(!$data){
			$this->error($Model->getError());
		}
		$this->assign("data",$data);
		$this->display();
	}
	public function dels(){
		$id = intval(I("get.id"));
		if($id<=1){
			$this->error("参数错误");
		}
		$Model = D("Role");
		$res = $Model->dels($id);
		if($res === false){
			$this->error("删除错误");
		}
		$this->success("删除成功",U("Role/index"));
	}
	public function edit(){
		$Model =D("Role");
		if(IS_GET){
			//显示修改
			$id = intval(I("get.id"));
			if($id<=1){
				$this->error("参数错误");
			}
			$data = $Model->findOneById($id);
			if($data === false){
				$this->error("数据错误");
			}
			$this->assign("data",$data);
			$this->display();
		}else{
			//处理修改
			$data = $Model->create();
			if(!$data){
				$this->error($Model->getError());
			}
			$res = $Model->update($data);
			if(!$res){
				$this->error("修改失败");
			}
			$this->success("修改成功",U("Role/Index"));
		}
	}
	public function disfetch(){
		if(IS_GET){
			//获取角色已有的权限
			$role_id = intval(I("get.id"));
			if($role_id <= 1){
				$this->error("参数错误");
			}
			$hasRules = D("RoleRule")->getRules($role_id);
			foreach ($hasRules as $key => $value) {
				$hasRuleIds[] = $value["rule_id"];
			}
			$this->assign("hasRuleIds",$hasRuleIds);
			
			//获取权限
			$Model = D("Rule");
			$data = $Model->getParentTree();
			$this->assign("data",$data);
			$this->display();
		}else{
			//角色id 权限id 
			$role_id = intval(I("post.role_id"));
			if($role_id <= 1){
				$this->error("参数错误");
			}
			$rule_id_list = I("post.rule_id");
			D("RoleRule")->disfetch($role_id,$rule_id_list);

			//修改角色权限时需要将当前角色对应的所有缓存文件删除
			//获取当前修改的角色下所有用户信息
			$user_info = D("AdminRole")->where("role_id=".$role_id)->select();
			foreach ($user_info as $key => $value) {
				S("user_".$value["admin_id"],null);
			}
			$this->success("赋予权限成功",U("index"));
		}
	}
	//清除超级管理员缓存文件
	public function flushAdmin(){
		//获取所有的超级管理员用户
		$user = M("AdminRole")->where("role_id=1")->select();
		//将所有的超级管理员用户对应的缓存文件删除
		foreach ($user as $key => $value) {
			S("user_".$value["admin_id"],null);
		}
		echo "OK";
		//输出提示
	}
}